<template>
  <!-- 添加或修改入库信息管理对话框 -->
  <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body :close-on-click-modal="false"
             v-dialogDrag>
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-tabs v-model="activeName" class="detail-tab" type="card">
        <el-tab-pane label="基本信息" name="first">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商品名称" prop="name">
                <el-select v-model="form.name" placeholder="请填写商品名称" clearable filterable ref="myselectGoodsName"
                           @change="updateInsertName"
                           :filter-method="updateInsertName"
                           style="width: 300px">
                  <el-option v-for="dict in GoodsNameOptions"
                             :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品品牌" prop="brand">
                <el-select v-model="form.brand" placeholder="请填写商品品牌" clearable filterable @change="updateInsertBrand"
                           :filter-method="updateInsertBrand"
                           style="width: 300px">
                  <el-option v-for="dict in GoodsBrandOptions" ref="myselectGoodsBrand"
                             :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="采购单价" prop="costPrice">
                <el-input-number :precision="2" v-model="form.costPrice" placeholder="请输入采购单价"
                                 @change="updateTotleCost()"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品型号" prop="model">
                <el-input v-model="form.model" placeholder="请输入商品型号"
                          style="width: 200px"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="采购数量" prop="count">
                <el-input-number v-model="form.count" placeholder="请输入采购数量" @change="updateRemainder()"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="库存数量" prop="remainderCount">
                <el-input-number v-model="form.remainderCount" placeholder="请输入库存数量" disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品单位" prop="unit">
                <el-input v-model="form.unit" placeholder="请输入商品入库单位"
                          style="width: 200px"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="采购总价" prop="cost">
                <el-input-number :precision="2" v-model="form.cost" placeholder="请输入采购总价" disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="采购方式" prop="buyType">
                <el-radio-group v-model="form.buyType">
                  <el-radio v-for="dict in dict.type.buy_type"
                            :key="dict.value" :label="dict.value">{{dict.label}}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="采购日期" prop="buyDate">
                <el-date-picker clearable
                                v-model="form.buyDate"
                                type="date"
                                value-format="yyyy-MM-dd"
                                :picker-options="pickerOptions"
                                placeholder="请选择采购日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="供应商" prop="supplierId">
                <el-select v-model="form.supplierId" placeholder="请选择供应商" filterable @change="selectSupplier" clearable
                           style="width: 300px">
                  <el-option v-for="dict in dict.type.goods_supplier" ref="myselectSsupplier"
                             :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="有效日期" prop="validityTerm">
                <el-date-picker clearable
                                v-model="form.validityTerm"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="请选择有效日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="有无含税发票" prop="invoiceTax">
                <!--<el-select v-model="form.invoiceTax" placeholder="请选择采购方式" @change="updateCostTax" clearable
                           style="width: 200px">
                  <el-option v-for="dict in dict.type.have_tax_invoice"
                             :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>-->
                <el-radio-group v-model="form.invoiceTax">
                  <el-radio v-for="dict in dict.type.have_tax_invoice" @change="updateCostTax"
                            :key="dict.value" :label="dict.value">{{dict.label}}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="含税单价" prop="costPriceTax">
                <el-input-number :precision="2" v-model="form.costPriceTax" placeholder="请输入含税单价" disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="含税总价" prop="costTax">
                <el-input-number :precision="2" v-model="form.costTax" placeholder="请输入采购总价" disabled/>
              </el-form-item>
            </el-col>
            <!--<el-col :span="12">
              <el-form-item label="采购人" prop="buyId">
                <el-select v-model="form.buyId" placeholder="请选择采购人" @change="selectUser" clearable
                           style="width: 300px">
                  <el-option v-for="dict in dict.type.sys_user" ref="myselectUser"
                             :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
              </el-form-item>
            </el-col>-->
            <el-col :span="12" v-if="form.id">
              <el-form-item label="是否报销" prop="reimburse">
                <el-select v-model="form.reimburse" placeholder="是否报销" clearable style="width: 300px" disabled>
                  <el-option v-for="dict in dict.type.yes_no"
                             :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="备注信息" prop="remark">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入备注信息"/>
              </el-form-item>
            </el-col>
            <!--<el-col :span="12">
              <el-form-item label="是否取得发票" prop="invoice">
                <el-select v-model="form.invoice" placeholder="是否取得发票" clearable style="width: 130px">
                  <el-option v-for="dict in dict.type.yes_no"
                             :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发票编号" prop="invoiceNo">
                <el-input v-model="form.invoiceNo" placeholder="请输入发票编号"/>
              </el-form-item>
            </el-col>-->
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm" v-if="showBtn">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
    import {addAction, getById, updateAction} from '@/api/manage';
    import request from "@/utils/request";
    import moment from 'moment';

    export default {
        name: "GoodsOrderInForm",
        dicts: ['yes_no', 'buy_type', 'goods_supplier', 'have_tax_invoice'],
        data() {
            return {
                // 遮罩层
                loading: true,
                activeName: "first",
                // 弹出层标题
                title: "",
                // 是否显示弹出层
                open: false,
                // 表单参数
                form: {},
                // 表单校验
                rules: {
                    name: [
                        {required: true, message: "商品名称不能为空", trigger: "blur"}
                    ],
                    brand: [
                        {required: true, message: "商品品牌不能为空", trigger: "blur"}
                    ],
                    costPrice: [
                        {required: true, message: "商品采购单价不能为空", trigger: "blur"}
                    ],
                    count: [
                        {required: true, message: "商品采购数量不能为空", trigger: "blur"}
                    ],
                    buyType: [
                        {required: true, message: "采购方式不能为空", trigger: "blur"}
                    ],
                    unit: [
                        {required: true, message: "商品单位不能为空", trigger: "blur"}
                    ],
                    supplierId: [
                        {required: true, message: "供应商信息不能为空", trigger: "blur"}
                    ],
                    buyDate: [
                        {required: true, message: "采购日期不能为空", trigger: "blur"}
                    ],
                    invoiceTax: [
                        {required: true, message: "有无含税发票不能为空", trigger: "blur"}
                    ],
                },
                url: {
                    getById: '/goodsOrderIn/goodsOrderIn/',
                    add: '/goodsOrderIn/goodsOrderIn/add',
                    edit: '/goodsOrderIn/goodsOrderIn/edit',
                },
                minus: 0,
                GoodsNameOptionOri: [],
                GoodsNameOptions: [],
                GoodsBrandOptionOri: [],
                GoodsBrandOptions: [],
                GoodsUnitOptionOri: [],
                GoodsUnitOptions: [],
                pickerOptions: {
                    disabledDate: this.disabledDate
                },
                showBtn: true,
            };
        },
        created() {

        },
        methods: {

            handleView(row) {
                this.showBtn = false;
                this.reset();
                const id = row.id || this.ids;
                getById(this.url.getById, id).then(response => {
                    this.form = response.data;
                    // this.minus = this.form.count - this.form.remainderCount;//查看详情后立即入库会导致库存剩余数量出错
                    this.open = true;
                    this.title = "查看入库信息";
                });
            },
            disabledDate(time) {
                let _now = Date.now();
                let sevenDaysAgo = moment(new Date()).subtract(7, 'days');
                return time.getTime() < new Date(sevenDaysAgo).getTime();
            },
            updateCostTax() {
                let that = this;
                let percent = 1;
                if (that.form.costPrice && that.form.invoiceTax) {
                    if (that.form.invoiceTax === "0") {
                        percent = 1.035;
                    } else {
                        percent = 1;
                    }
                    let costPriceTax = that.functionNumberMul(that.form.costPrice, percent).toFixed(2);
                    that.$set(that.form, "costPriceTax", costPriceTax);
                    let costTax = that.functionNumberMul(that.form.count, costPriceTax);
                    that.$set(that.form, "costTax", costTax);
                } else {
                    let costPriceTax = 0;
                    that.$set(that.form, "costPriceTax", costPriceTax);
                    let costTax = 0;
                    that.$set(that.form, "costTax", costTax);
                }
            },
            initOrderInDicts() {
                let that = this;
                request({
                    url: '/goodsOrderIn/goodsOrderIn/initOrderInDicts',
                    method: 'get',
                    params: {}
                }).then(res => {
                    // console.log(res)
                    that.GoodsNameOptionOri = res.data.nameList;
                    that.GoodsNameOptions = res.data.nameList;
                    that.GoodsBrandOptionOri = res.data.brandList;
                    that.GoodsBrandOptions = res.data.brandList;
                })
            },
            updateInsertName(val1) {
                let that = this;
                if (val1) {
                    that.GoodsNameOptions = that.GoodsNameOptionOri.filter(item => item.dictLabel.indexOf(val1) > -1)
                } else {
                    that.GoodsNameOptions = that.GoodsNameOptionOri
                }
                that.$set(that.form, "name", val1);
            },
            updateInsertBrand(val1) {
                let that = this;
                if (val1) {
                    that.GoodsBrandOptions = that.GoodsBrandOptionOri.filter(item => item.dictLabel.indexOf(val1) > -1)
                } else {
                    that.GoodsBrandOptions = that.GoodsBrandOptionOri
                }
                that.$set(that.form, "brand", val1);
            },
            updateTotleCost() {
                let that = this;
                if (that.form.count && that.form.costPrice) {
                    let totleCost = that.functionNumberMul(that.form.count, that.form.costPrice);
                    that.$set(that.form, "cost", totleCost);
                }
                that.updateCostTax();
            },
            updateRemainder() {
                let that = this;
                let newCount = that.form.count;
                let remainder = newCount - that.minus;
                that.form.remainderCount = remainder;
                if (that.form.count && that.form.costPrice) {
                    let totleCost = that.functionNumberMul(that.form.count, that.form.costPrice);
                    that.$set(that.form, "cost", totleCost);
                }
                that.updateCostTax();
            },
            functionNumberMul(arg1, arg2) {
                var m = 0;
                var s1 = arg1.toString();
                var s2 = arg2.toString();
                try {
                    m += s1.split(".")[1].length;
                } catch (e) {
                }
                try {
                    m += s2.split(".")[1].length;
                } catch (e) {
                }
                let c1 = Number(s1.replace(".", ""));
                let c2 = Number(s2.replace(".", ""));
                let c3 = Math.pow(10, m);
                return c1 * c2 / c3;
            },
            selectSupplier(value) {
                let that = this;
                that.$nextTick(() => {
                    let arr = that.$refs.myselectSsupplier;
                    for (let i = 0; i < arr.length; i++) {
                        if (arr[i].currentValue == value) {
                            that.form.supplierName = arr[i].label;
                        }
                    }
                })
                // console.log(that.form.buyName);
            },
            /*selectUser(value) {
                let that = this;
                that.$nextTick(() => {
                    let arr = that.$refs.myselectUser;
                    for (let i = 0; i < arr.length; i++) {
                        if (arr[i].currentValue == value) {
                            that.form.buyName = arr[i].label;
                        }
                    }
                })
            },*/
            // 取消按钮
            cancel() {
                this.open = false;
                this.reset();
            },
            // 表单重置
            reset() {
                this.form = {
                    id: null,
                    name: null,
                    brand: null,
                    unit: null,
                    costPrice: null,
                    count: null,
                    remainderCount: null,
                    cost: null,
                    validityTerm: null,
                    buyId: this.$store.getters.userId,
                    buyName: this.$store.getters.nickName,
                    buyDate: new Date(),
                    buyType: "0",
                    reimburse: '0',
                    supplierId: null,
                    supplierName: null,
                    delFlag: null,
                    createBy: null,
                    createTime: null,
                    updateBy: null,
                    updateTime: null,
                    costPriceTax: 0,
                    costTax: 0,
                    remark: null,
                    deptId: this.$store.getters.deptId,
                    deptName: this.$store.getters.deptName,
                };
                this.resetForm("form");
            },
            /** 新增按钮操作 */
            handleAdd() {
                this.reset();
                this.initOrderInDicts();
                this.showBtn = true;
                this.open = true;
                this.title = "添加入库信息";
            },
            /** 修改按钮操作 */
            handleUpdate(row) {
                this.reset();
                this.initOrderInDicts();
                this.showBtn = true;
                const id = row.id || this.ids;
                getById(this.url.getById, id).then(response => {
                    this.form = response.data;
                    this.minus = this.form.count - this.form.remainderCount;
                    this.open = true;
                    this.title = "修改入库信息";
                });
            },
            /** 提交按钮 */
            submitForm() {
                let that = this;
                that.$refs["form"].validate(valid => {
                    if (valid) {
                        that.GoodsNameOptions = that.GoodsNameOptionOri;
                        that.GoodsBrandOptions = that.GoodsBrandOptionOri
                        if (that.form.id != null) {
                            updateAction(that.url.edit, that.form).then(response => {
                                that.$modal.msgSuccess("修改成功");
                                that.open = false;
                                that.$emit('ok');
                            });
                        } else {
                            addAction(that.url.add, that.form).then(response => {
                                that.$modal.msgSuccess("新增成功");
                                that.open = false;
                                that.$emit('ok');
                            });
                        }
                    }
                });
            },
        }
    };
</script>
